package com.yq.tanhua.ui.userinfo

import android.app.AlertDialog
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.text.TextUtils
import android.widget.DatePicker
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import coil.compose.rememberAsyncImagePainter
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SizeUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.yq.tanhua.ui.TanHuaBaseActivity
import com.yq.tanhua.ui.login.viewmodel.LoginViewModel
import config.TanHua_settting_info
import java.util.*
import kotlin.collections.ArrayList


@Route(path = TanHua_settting_info)
class UserInfoSettting : TanHuaBaseActivity() {

    lateinit var mViewModel: UserInfoViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(this)[UserInfoViewModel::class.java]

        setContent {

            LaunchedEffect(Unit) {
                mViewModel.viewIntent.collect {
                    when (it) {
                        is ViewIntent.SaveSuccess -> {
                            Toast.makeText(baseContext, "保存数据成功", Toast.LENGTH_SHORT).show()
                            finish()
                        }
                    }
                }
            }


            Column {
                Title()
                content()
            }
        }

        mViewModel.dispatch(UserInfoIntent.GetUserInfo)
    }


    @Composable
    @Preview
    fun Title() {
        val navBarHeight: Int = BarUtils.getStatusBarHeight()
        Box(
            modifier = Modifier
                .fillMaxWidth(1f)
                .background(Color.Gray)
                .padding(top = SizeUtils.px2dp(navBarHeight.toFloat()).dp, bottom = 10.dp)
        ) {
            Text(
                text = "信息设置", color = Color.White, fontSize = 20.sp,
                modifier = Modifier.align(Alignment.Center)
            )
            Icon(
                Icons.Rounded.ArrowBack,
                contentDescription = "",
                tint = Color.White,
                modifier = Modifier
                    .align(Alignment.CenterStart)
                    .padding(start = 15.dp)
                    .clickable {
                        finish()
                    },
            )
        }
    }


    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    @Preview
    fun content() {

        val userInfoState = mViewModel.userInfoUIState.collectAsState()

        LaunchedEffect(null) {
            mViewModel.viewIntent.collect {
                when (it) {
                    is ViewIntent.UploadHead -> {
                        Toast.makeText(baseContext, "上传：${it.isSucess}", Toast.LENGTH_SHORT).show()
                        hideLoadingDialog()
                    }
                }

            }
        }
        val sexTag = arrayListOf("男", "女")
        Column(modifier = Modifier.padding(30.dp)) {

            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .clickable {
                        selectPic()
                    }
            ) {
                if (!TextUtils.isEmpty(userInfoState.value.headImage)) {
                    Image(
                        painter = rememberAsyncImagePainter(model = userInfoState.value.headImage),
                        contentDescription = null,
                        modifier = Modifier.size(100.dp, 100.dp)
                    )
                } else {
                    Image(
                        imageVector = Icons.Default.Info, contentDescription = "头像",
                        modifier = Modifier
                            .size(100.dp, 100.dp)
                    )
                }
                Text(text = "选择头像")
            }

            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(text = "设置昵称")
                TextField(
                    value = userInfoState.value.nickName,
                    label = { Text(text = "请输入昵称") },
                    onValueChange = { result ->
                        mViewModel.dispatch(UserInfoIntent.UpdateNickName(result))
                    },
                    modifier = Modifier
                        .padding(start = 20.dp)
                        .background(Color.White),
                    colors = TextFieldDefaults.textFieldColors(
                        containerColor = Color.Transparent,
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    )
                )
            }

            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(text = "选择性别")
                Row {
                    sexTag.forEach {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            RadioButton(selected = userInfoState.value.sex == it, onClick = {
                                mViewModel.dispatch(UserInfoIntent.UpdateSex(it))
                            })
                            Text(text = it)
                        }
                    }
                }
            }

            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(text = "设置居住地")
                TextField(
                    value = userInfoState.value.address,
                    label = { Text(text = "请输入所在城市") },
                    onValueChange = { result ->
                        mViewModel.dispatch(UserInfoIntent.UpdateAddress(result))
                    },
                    modifier = Modifier
                        .padding(start = 20.dp)
                        .background(Color.White),
                    colors = TextFieldDefaults.textFieldColors(
                        containerColor = Color.Transparent,
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    )
                )
            }

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(top = 20.dp)
                    .clickable { showDataPick() }) {
                Text(text = "设置生日")
                Spacer(modifier = Modifier.weight(1f))
                Text(text = userInfoState.value.birthDate)
                Icon(imageVector = Icons.Rounded.ArrowForward, contentDescription = "")
            }


            Button(
                onClick = { saveUserInfo() },
                modifier = Modifier
                    .padding(vertical = 20.dp)
                    .align(Alignment.CenterHorizontally)
            ) {
                Text(text = "保存用户信息")
            }

        }
    }


    fun selectPic() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let {
                        it[0]?.let {
                            mViewModel.dispatch(UserInfoIntent.UpdateHead(it.realPath))
                            showLoadingDialog()
                        }
                    }
                }

                override fun onCancel() {}
            })
    }

    var uploadingDialog: AlertDialog? = null;

    fun showLoadingDialog() {
        uploadingDialog = AlertDialog.Builder(this).setMessage("头像uploading").show()
    }

    fun hideLoadingDialog() {
        uploadingDialog?.dismiss()
    }

    fun showDataPick() {

        val calendar = Calendar.getInstance(Locale.CHINA)
        DatePickerDialog(
            this,
            object : OnDateSetListener {
                override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                    mViewModel.dispatch(UserInfoIntent.UpdateBirth("$year-${month + 1}-$dayOfMonth"))
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    fun saveUserInfo() {
        mViewModel.dispatch(UserInfoIntent.SaveUserInfo)
    }


}